package com.czwx.bee.business.manager.modular.sys.service.impl;

import com.czwx.bee.base.common.exception.BizExceptionEnum;
import com.czwx.bee.base.common.exception.BusinessException;
import com.czwx.bee.base.common.interfaces.BpUserStatusEnum;
import com.czwx.bee.business.manager.modular.sys.model.SecurityUser;
import com.czwx.bee.business.manager.modular.sys.model.User;
import com.czwx.bee.business.manager.modular.sys.service.ResourceService;
import com.czwx.bee.business.manager.modular.sys.service.RoleService;
import com.czwx.bee.business.manager.modular.sys.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

/**
 * Spring Security UserDetailsService实现
 * 
 * @author Wiki
 * @data 2018年4月8日 下午5:44:09
 */
@Service
public class AuthenticationApiImpl implements UserDetailsService {

	@Autowired
	private ResourceService resourceService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private UserService userService;

	@Override
	public SecurityUser loadUserByUsername(String username) throws UsernameNotFoundException {
        SecurityUser securityUser=userService.getAuthUser(username);

		if (securityUser == null) {
			throw new BusinessException(BizExceptionEnum.NO_THIS_USER);
		}
		if(securityUser.getStatus()==BpUserStatusEnum.Discontinuation.getCode()){
			throw new BusinessException(BizExceptionEnum.ACCOUNT_UNENABLE);
		}

		Collection<GrantedAuthority> authorities = new ArrayList<>();
		resourceService.findUserResourceByUid(securityUser.getId(),1).forEach((Map roleList)->{
			GrantedAuthority authority = new SimpleGrantedAuthority((String) roleList.get("url"));
			authorities.add(authority);
		});
		securityUser.setGrantList(authorities);
		securityUser.setResourceList(resourceService.findUserResourceByUid(securityUser.getId(),1));

		return securityUser;
	}

}
